//
//  HZSearchView.m
//  HZTC_Stock
//
//  Created by MayerF on 17/3/14.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZSearchView.h"
#import "MYCustomKeyboardTextField.h"
#import "MYSearchResultTableViewCell.h"
#import "HZSearchTool.h"
//#import "ZQHttpManager.h"

#define KSearchCellH 45
#define kTextFieldH 30

@interface HZSearchView()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic, strong)UIImageView                *pNavBackgroudImageView;
@property (nonatomic, strong)MYCustomKeyboardTextField  *pCustomKeyboardTextField;
@property (nonatomic, strong)UIButton                   *pCancelButton;
@property (nonatomic, strong)UIImageView                *pLeftView;
@property (nonatomic, strong)UIButton                   *pRightView;
@property (nonatomic, strong)UITableView                *pStockListTableView;
@property (nonatomic, strong)UILabel                    *pStockListNOResult;//没有搜索结果
@property (nonatomic, strong)UILabel                    *pSearchHistoryLabel;
@property (nonatomic, strong)UIButton                   *buttonClearHistory;
@property (nonatomic, assign)KMSSearchType               searchType;
@property (nonatomic, strong)NSMutableArray             *pListData;
@end

@implementation HZSearchView
-(UIImageView *)pLeftView
{
    if (!_pLeftView) {
        _pLeftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kTextFieldH, kTextFieldH)];
    }
    return _pLeftView;
}
-(UIButton *)pRightView
{
    if (!_pRightView) {
        _pRightView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kTextFieldH, kTextFieldH)];
    }
    return _pRightView;
}
- (UIButton *)buttonClearHistory
{
    if (_buttonClearHistory == nil) {
        _buttonClearHistory = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 40.0f)];
        [_buttonClearHistory setTitle:@"点此清除浏览记录" forState:UIControlStateNormal];
        [_buttonClearHistory setTitleColor:kMYHexToRGB(0x999999, 1) forState:UIControlStateNormal];
        _buttonClearHistory.backgroundColor = kMYHexToRGB(0xefefef, 1);
        _buttonClearHistory.titleLabel.font = [UIFont systemFontOfSize:14];
        [_buttonClearHistory setImage:[UIImage imageNamed:@"remove_unselected11"] forState:UIControlStateNormal];
        [_buttonClearHistory addTarget:self action:@selector(buttonClearEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonClearHistory;
}
- (UILabel *)pSearchHistoryLabel
{
    if (!_pSearchHistoryLabel) {
        _pSearchHistoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 64 + 20, self.frame.size.width-30, 30)];
        _pSearchHistoryLabel.text = @"    最近浏览";
        _pSearchHistoryLabel.textAlignment = NSTextAlignmentLeft;
        _pSearchHistoryLabel.textColor = kMYHexToRGB(0x999999, 1);
        _pSearchHistoryLabel.backgroundColor = kMYHexToRGB(0xe8e8e8, 1);
        _pSearchHistoryLabel.font = [UIFont systemFontOfSize:14];
    }
    return _pSearchHistoryLabel;
}
#pragma mark -
#pragma mark 生命周期
- (instancetype)init{
    self = [super init];
    if (self) {
        [self p_commonInit];
        self.backgroundColor = kMYHexToRGB(0xe8e8e8, 1);
    }
    return self;
}
#pragma mark -
#pragma mark public
- (void)showKeyboard
{
    [_pCustomKeyboardTextField becomeFirstResponder];
}
#pragma mark -
#pragma mark private
- (void)p_commonInit
{
    _pNavBackgroudImageView = [UIImageView new];
    _pCustomKeyboardTextField = [MYCustomKeyboardTextField new];
    _pCancelButton = [UIButton new];
    _pStockListTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    _pNavBackgroudImageView.userInteractionEnabled = YES;
    _pCustomKeyboardTextField.delegate = self;
    _pStockListTableView.dataSource = self;
    _pStockListTableView.delegate = self;
//    _pNavBackgroudImageView.layer.borderWidth = 0.5;
//    _pNavBackgroudImageView.layer.borderColor = [kMYHexToRGB(0xbbbbbb, 1) CGColor];
    _pNavBackgroudImageView.backgroundColor = kMYHexToRGB(0xef1d2e, 1);
    _pStockListTableView.backgroundColor = kMYHexToRGB(0xe8e8e8, 1);
    [_pCancelButton addTarget:self action:@selector(cancelButtonOnClick) forControlEvents:UIControlEventTouchUpInside];
    [_pCancelButton setTitle:kHZCancel forState:UIControlStateNormal];
    [_pCancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _pCancelButton.titleLabel.font = [UIFont systemFontOfSize:13];
    self.pLeftView.image = [UIImage imageNamed:@"search"];
    _pLeftView.contentMode = UIViewContentModeCenter;
    
    [self.pRightView setImage:[UIImage imageNamed:@"clear"] forState:UIControlStateNormal];
    _pRightView.imageView.contentMode = UIViewContentModeCenter;
    [_pRightView addTarget:self action:@selector(clearOnClick) forControlEvents:UIControlEventTouchUpInside];
    
    _pCustomKeyboardTextField.inputMaxLength = 6;
    _pCustomKeyboardTextField.leftView = _pLeftView;
    _pCustomKeyboardTextField.rightView = _pRightView;
    _pCustomKeyboardTextField.font = [UIFont systemFontOfSize:13];
    _pCustomKeyboardTextField.leftViewMode = UITextFieldViewModeAlways;
    _pCustomKeyboardTextField.rightViewMode = UITextFieldViewModeWhileEditing;
    [_pCustomKeyboardTextField setCustomKeyboardMode:KMYKeyboard_Custom_Mode];
    [_pCustomKeyboardTextField setCustomKeyboardType:KMYCustomKeyboard_Number_Type];
    _pCustomKeyboardTextField.backgroundColor = kMYHexToRGB(0xe8e8e8, 0.5);
    _pCustomKeyboardTextField.textColor = [UIColor whiteColor];
    _pCustomKeyboardTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:kHZPlaceHolder attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    _pCustomKeyboardTextField.layer.cornerRadius = kTextFieldH/2;
    _pCustomKeyboardTextField.layer.masksToBounds = YES;
    _pStockListTableView.tableFooterView = [UIView new];
    
    [_pCustomKeyboardTextField addTarget:self action:@selector(customTextFieldChanged:) forControlEvents:UIControlEventValueChanged];
    
    [self addSubview:_pNavBackgroudImageView];
    [self addSubview:_pCustomKeyboardTextField];
    [self addSubview:_pCancelButton];
    [self addSubview:_pStockListTableView];
    
    [self p_initConstraints];
    
    _pListData = [NSMutableArray array];
}

- (void)setDefaultCode:(NSString *)defaultCode
{
    _defaultCode = defaultCode;
    if (_defaultCode) {
        _pCustomKeyboardTextField.text = _defaultCode;
        [self customTextFieldChanged:_pCustomKeyboardTextField];
    }
}

- (void)p_initConstraints
{
    if (IPHONE_X) {
        [_pNavBackgroudImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self);
            make.left.mas_equalTo(self);
            make.right.mas_equalTo(self);
            make.height.mas_equalTo(64 + 24);
        }];
        [_pCustomKeyboardTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_pNavBackgroudImageView).offset(25 + 24);
            make.left.mas_equalTo(_pNavBackgroudImageView).offset(10);
            make.right.mas_equalTo(_pNavBackgroudImageView).offset(-60);
            make.height.mas_equalTo(kTextFieldH);
        }];
    }else {
        [_pNavBackgroudImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self);
            make.left.mas_equalTo(self);
            make.right.mas_equalTo(self);
            make.height.mas_equalTo(64);
        }];
        [_pCustomKeyboardTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_pNavBackgroudImageView).offset(25);
            make.left.mas_equalTo(_pNavBackgroudImageView).offset(10);
            make.right.mas_equalTo(_pNavBackgroudImageView).offset(-60);
            make.height.mas_equalTo(kTextFieldH);
        }];
    }
    [_pCancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pCustomKeyboardTextField);
        make.left.mas_equalTo(_pCustomKeyboardTextField.mas_right);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(kTextFieldH);
    }];
    [_pStockListTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pNavBackgroudImageView.mas_bottom);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.bottom.mas_equalTo(self);
    }];
}

- (void)p_loadShowNoData
{
    if (!_pStockListNOResult) {
        _pStockListNOResult = [UILabel new];
        _pStockListNOResult.text = @"无搜索结果";
        _pStockListNOResult.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_pStockListNOResult];
    }
    [_pStockListNOResult mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self);
        make.centerY.mas_equalTo(_pNavBackgroudImageView.mas_bottom).offset(50);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(50);
    }];
}

- (void)buttonClearEvent:(UIButton *)button
{
    [HZSearchTool searchDeleteHistoryStock];
    [_pListData removeAllObjects];
    [_pStockListTableView reloadData];
}

- (void)cancelButtonOnClick
{
    [self endEditing:YES];
    [self.parent upToParentWithObjc:self withType:kHZ_dismissSearchVC_Action withParamter:nil];
}

- (void)clearOnClick
{
    self.pCustomKeyboardTextField.text = nil;
    [self textFieldShouldClear:self.pCustomKeyboardTextField];
}

- (void)customTextFieldChanged:(UITextField *)textField
{
    DLog(@"textField===%@",textField.text);
    _pStockListNOResult.hidden = YES;
    NSString *pText = textField.text;
    if ([pText isEqualToString:@""]) {
        [self textFieldShouldBeginEditing:textField];
        return;
    }
    [_pListData removeAllObjects];
    [HZSearchTool searchStockDictWithSearchInfo:textField.text success:^(NSArray *result) {
        DLog(@"searchStockDictWithSearchInfo==%@",result);
        if (result.count > 0) {
            _searchType = KMSSearch_result_Type;
            [_pListData addObjectsFromArray:result];
        }else {
            [self p_loadShowNoData];
            _pStockListNOResult.hidden = NO;
        }
        [_pStockListTableView reloadData];
    }];
}

#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    self.searchType = KMSSearch_history_Type;
    NSString *pText = textField.text;
    if (![pText isEqualToString:@""]) {
        return YES;
    }
    
    [_pListData removeAllObjects];
    NSArray *list = [HZSearchTool searchGetHistoryStock];
    [_pListData addObjectsFromArray:list];
    [_pStockListTableView reloadData];
    
    return YES;
}

-(BOOL)textFieldShouldClear:(UITextField *)textField{
    textField.text = @"";
    _pStockListNOResult.hidden = YES;
    return [self textFieldShouldBeginEditing:textField];
}
- (BOOL)checkIsLogined
{
    BOOL isLogined = [HZUserManager manager].isLogined;
    if (!isLogined) {
        UIViewController *nextVC = [[MYRouter shared] matchController:kRouterLogin];
        [self.parent presentViewController:nextVC animated:YES completion:nil];
    }
    return isLogined;
}
#pragma mark -
#pragma mark UIScrollViewSource
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_pCustomKeyboardTextField resignFirstResponder];
}
#pragma mark -
#pragma mark UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.searchType == KMSSearch_history_Type && (self.pListData.count > 0 || self.pListData.count == 0)) {
        return CGRectGetHeight(self.pSearchHistoryLabel.frame);
    }else if (self.searchType == KMSSearch_result_Type){
        return 0;
    }
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (self.searchType == KMSSearch_history_Type && self.pListData.count > 0 ) {
        return CGRectGetHeight(self.buttonClearHistory.frame);
    }
    return 0.01f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.searchType == KMSSearch_history_Type && (self.pListData.count > 0 || self.pListData.count == 0) ) {
        return self.pSearchHistoryLabel;
    }else if (self.searchType == KMSSearch_result_Type){
        return nil;
    }
    return nil;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (self.searchType == KMSSearch_history_Type && self.pListData.count > 0 ) {
        return self.buttonClearHistory;
    }
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.pListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    tableView.separatorColor = kMYHexToRGB(0xdddddd, 1);
    
    MYSearchResultModel *model = self.pListData[indexPath.row];
    if (_isFromCreate) {
        model.m_isCreated = YES;
    }
    if (![HZUserManager manager].isLogined) {
        model.m_isSelected = NO;
    }
    MYSearchResultTableViewCell *pSearchCell = [MYSearchResultTableViewCell searchResultCellTableView:tableView indexPath:indexPath cellModel:model cellHight:KSearchCellH cellW:self.frame.size.width];
    __weak typeof (self)weakSelf = self;
    [pSearchCell addClickOnButtonBlockBack:^(UIButton *btn) {
        if (![weakSelf checkIsLogined]) {return;}
        if (weakSelf.isFromCreate) {
            [weakSelf.parent upToParentWithObjc:weakSelf withType:kHZ_createPolicy_Action withParamter:@[model.m_stockCode, @(model.n_TradeId)]];
            return;
        }
        if (btn.selected) {
//            [ZQHttpManager deleteLocalCodeNetWork:NotNilStr(model.m_stockCode) andMarkrt:[NSString stringWithFormat:@"%d",model.n_TradeId] andSuccess:^(NSDictionary * _Nonnull reslutDic) {
//
//            } andFailed:^(NSError * _Nullable error, NSDictionary * _Nullable resultDic) {
//
//            }];
//            [HZNetworkTool networkDeleteOwnStock:model.m_stockCode WithMarketId:model.n_TradeId];
        }else {
//            [HZNetworkTool networkAddOwnStock:model.m_stockCode WithMarketId:model.n_TradeId];
//            [ZQHttpManager addLocalCodeNetWork:NotNilStr(model.m_stockCode) andMarkrt:[NSString stringWithFormat:@"%d",model.n_TradeId] andSuccess:^(NSDictionary * _Nonnull reslutDic) {
//                
//            } andFailed:^(NSError * _Nullable error, NSDictionary * _Nullable resultDic) {
//                
//            }];
            [HZNetworkTool speicalAddOwnStock:@{@"code": model.m_stockCode, @"market": [NSString stringWithFormat:@"%d", model.n_TradeId], @"name": model.m_stockName}];
        }
        [weakSelf p_uploadRequest];
        model.m_isSelected = !btn.selected;
        [weakSelf.pStockListTableView reloadData];
    }];
    
    return pSearchCell;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return KSearchCellH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_pListData.count - 1 < indexPath.row) { return;}
    
    MYSearchResultModel *searchModel = _pListData[indexPath.row];
    HZOwnedStockModel *ownModel = [HZOwnedStockModel new];
    ownModel.model_Name = searchModel.m_stockName;
    ownModel.model_Code = searchModel.m_stockCode;
    ownModel.nModel_Market = searchModel.n_TradeId;
    
    [HZSearchTool searchAddStockHistory:searchModel];
    [self.parent upToParentWithObjc:self withType:kHZ_jumpSingleStock_Action withParamter:ownModel];
}

-(void)dealloc {
    DLog(@"11");
}

- (void)setIsFromCreate:(BOOL)isFromCreate
{
    _isFromCreate = isFromCreate;
}

// 上传自选股
- (void)p_uploadRequest
{
//    NSArray *arr = [HZNetworkTool specialGetStocks];
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                          @"300031", kAPIFuctionKey,
//                          arr, @"param",
//                          nil];
//    [HZApiManager apiPostParams:dict success:^(id objc) {
//        
//    } failure:^(NSError *error) {
//        [SVProgressHUD showErrorWithStatus:error.domain];
//    }];
}

@end
